<template>
	<view>
		<!-- 收货人 -->
		<view class="gap"></view>
		<use-list-title v-if="!(addrData && addrData.id)" color="#333" title="选择收货人" iconfont="icondizhi-"
			@goto="toaddr"></use-list-title>
		<view v-else class="padding dflex-b bg-main" @click="toaddr">
			<view class="dflex">
				<view class="iconfont icondizhi- margin-right ft-main"></view>
				<view class="w-full dflex-wrap-w">
					<view class="margin-bottom-xs">
						<text>{{ addrData.provincial }}{{addrData.city}} {{ addrData.address }}</text>
					</view>
					<view>
						<text>{{ addrData.nickName }}</text>
						<text class="margin-left">{{ addrData.mobile }}</text>
					</view>
				</view>
			</view>

			<view class="iconfont iconjiantou-01 fs-sm"></view>
		</view>
		<view class="gap"></view>

		<view class="goods-area bg-main padding">
			<!-- 商品列表 -->
			<view class="goods-item" :class="{ 'margin-top': index > 0 }" v-for="(item, index) in goodsDatas"
				:key="index">
				<view class="pos-r">
					<image mode="aspectFill" :src="item.defaultImg"></image>
				</view>
				<view class="flex1 padding-left-sm">
					<text class="title clamp-2">{{ item.title || '' }}</text>
					<!-- 					<view class="ft-dark fs-xs padding-top-xs">
						<text v-if="cart_ids && cart_ids.length > 0" class="margin-right">×
							{{item.cart.goods_num}}</text>
						{{ (item.goods_sku && item.goods_sku.spec) || '&nbsp;&nbsp;' }}
					</view> -->
					<view class="pos-r dflex-b padding-top">
						<view class="price flex1">{{ (item.sprice) || '' }}</view>
						<!-- + - 数量 -->
						<use-number-box :min="item.pcount" :max="item.pcount" :value="item.pcount" :index="index"
							direction="right"></use-number-box>
					</view>
				</view>
			</view>
		</view>
		<view class="gap"></view>

		<!-- 优惠券 -->
		<use-list-title title="优惠券" :tip="couponName" color="#333" iconfont="iconyouhui" @goto="couponShow = true">
		</use-list-title>
		<!-- 优惠券弹出层 -->
		<use-popup mode="bottom" v-model="couponShow" @open="couponOpen">
			<!-- 优惠券区 -->
			<view class="coupon-area padding bg-drak">
				<view class="coupon-item bg-main pos-r fs-xs" v-for="(item, index) in couponDatas" :key="index">
					<view class="content pos-r padding dflex-b">
						<view class="">
							<view class="margin-bottom-xs fs">{{ item.title }}</view>
							<view class="ft-dark">有效期至 {{ item.end_time.split(' ')[0] }}</view>
						</view>
						<view class="tar">
							<view v-if="item.price >= 1" class="margin-bottom-xs price">{{ item.price }}</view>
							<view v-else class="margin-bottom-xs price">{{ item.price * 10 }}折</view>
							
							<view v-if="item.price >= 1" class="ft-dark">直减{{ item.price }}</view>
							<view v-else class="ft-dark">不限</view>
						</view>

						<view class="circle l"></view>
						<view class="circle r"></view>
					</view>
					<view class="dflex-b">
						<text v-if="item.type == 0" class="ft-dark padding-lr">{{ "折扣券" }}</text>
						<text v-if="item.type == 1" class="ft-dark padding-lr">{{ "直减券" }}</text>
						<text class="ft-base padding-tb-sm padding-lr" @click="couponUse(item)">立即使用</text>
					</view>
				</view>
				<view v-if="!couponDatas || couponDatas.length <= 0" class="coupon-none">
					<text class="coupon-none-tip">暂无优惠券</text>
				</view>
			</view>
		</use-popup>
		<view class="gap"></view>

		<!-- 金额明细 -->
		<view class="bg-main">
			<view class="dflex-b padding-lr padding-tb-sm">
				<view class="flex1">总金额</view>
				<view class=""><text style="font-size: 24rpx;">￥</text>{{ goods_money }}</view>
			</view>

			<view v-if="total_coupon_money > 0" class="dflex-b padding-lr padding-tb-sm">
				<view class="flex1">优惠金额</view>
				<view class="ft-base">-￥{{ total_coupon_money }}</view>
			</view>

			<view class="dflex-b padding-lr padding-tb-sm">
				<view class="margin-right-xl">备注</view>
				<input class="flex1 padding-sm" type="text" v-model="order_desc" placeholder="请填写买家备注"
					placeholder-class="placeholder" />
			</view>
		</view>
		<view class="gap"></view>

		<!-- 底部  -->
		<view class="oper-area pos-f pos-bottom w-full dflex-b bg-main safe-area-inset-bottom padding-left">
			<view>
				<text class="fs-sm">实付款</text>
				<text class="price margin-left-sm fs-xl">{{ total_money }}</text>
			</view>
			<view class="submit dflex-c bg-base fs animated-all" :class="is_submit === 1 ? 'bg-disabled' : ''"
				@click="submit">提交订单并支付</view>
		</view>
	</view>
</template>

<script>
	import {
		queryJiesProducts,
		createOrdersApi,
		queryDefAddrApi,
	} from '@/api/shopping.js'

	import {
		queryUserCouponsApi,
		
		//修改用户拥有的优惠券状态
		updateUserCouponsApi,
	} from '@/api/coupon.js'
	


	import {
		mapState
	} from 'vuex';


	// 收获人地址
	const _address = 'usemall-member-address'
	export default {
		computed: {
			...mapState(['islogin', 'member'])
		},

		data() {
			return {
				// 收货地址
				addrData: {},
				// 商品数据
				goodsDatas: [],
				// 产品金额
				goods_money: 0,

				// 优惠券
				couponShow: false,
				couponName: '选择优惠券',
				couponDatas: [],
				// 优惠券类型 直减|折扣  1|0
				coupon_type: 1,
				
				// 优惠券金额
				coupon_money: 0,
				
				// 实付金额
				total_money: 0,
				// 优惠金额
				total_coupon_money: 0,

				// 购物车 ids
				cart_ids: [],
				// 商品 id
				goods_id: 0,
				// 商品数量
				goods_num: 1,
				// 商品 sku id
				goods_sku_id: 0,
				// 使用优惠券ID
				order_coupon_id: 0,
				// 买家备注
				order_desc: '',

				is_submit: 1,
				platform: '',
				platform_name: ''
			};
		},
		onLoad(options) {
			let _this = this;
			this.$api.get_env(res => {
				this.platform = res.platform;
				this.platform_name = res.platform_name;
			});

			// if(options.goods_id){
			// 	// 商品 ids
			// 	this.goods_id = options.goods_id || '';
			// 	// 购物车 ids
			
			// 	this.getJiesProductsFunc();
			// }
			
				if (options.cart_ids) {
					this.cart_ids = options.cart_ids.split(',');
				}
			
			// 商品 sku
			// this.goods_sku_id = options.sku_id || '';

			
			// this.getJiesProductsFunc();
			// // 加载商品数据
			this.loadData();
			// 计算实际支付 总金额
			this.calcTotalMoney();
			//获取默认地址
			this.getDefAddrFunc(); 
			
			uni.$on('__event_choice_address', data => {
				this.addrData = data;
				
			});
		},
		onShow() {
			if (this.addrData && this.addrData.id) return;
			// this.$db[_address].where('create_uid == $env.uid').tofirst()
			// 	.then(res => {
			// 		console.log('res', res);
			// 		if (res && res.code === 200) {
			// 			this.addrData = res.datas;
			// 		}
			// 	})
			

		},
		methods: {
			// 加载数据
			async loadData() {
				await this.getJiesProductsFunc();

				// this.$func.usemall.call('goods/detail2order', {
				// 	cart_ids: this.cart_ids,
				// 	goods_id: this.goods_id,
				// 	goods_sku_id: this.goods_sku_id
				// }).then(res => {
				// 	if (res.code === 200) {
				// 		this.goodsDatas = res.datas;
				// 		this.calcTotalMoney();
				// 		this.is_submit = 0;
				// 		return;
				// 	}

				// 	this.$api.msg(res.msg);
				// })
				console.log("=================================");
				this.calcTotalMoney();
			},

			async getJiesProductsFunc() {
				const response = await queryJiesProducts({
					uid: this?.member?.id ?? "",
					cart_ids: this?.cart_ids ?? [],
				}).catch(() => {})
				if (response?.code === 200) {
					this.is_submit = 0;
					console.debug(response, "<===============response.goodsDatas")
					console.debug(this.cart_ids, "<===============goodsDatas.this?.cart_ids")
					console.debug(this.member.id, "<===============goodsDatas.this.member.id")
					// this.cartDatas = response?.data ?? [];
					const _data = response?.data?.length > 0 ? response.data[0].products : [];
					_data.map(item => {
						item.pcount = 0;
						item.sprice = 0;
						if (item?.shoppingcarts_products) {
							item.pcount = item?.shoppingcarts_products?.pcount ?? 0;
							item.sprice = parseFloat(item?.shoppingcarts_products?.sprice ?? 0).toFixed(2);
						}
					})
					this.goodsDatas = _data;
					console.log(this.goodsDatas, "<==============this.goodsDatas")
					// this.calcTotalMoney();
				} else {
					this.goodsDatas = [];
				};
			},
			
			async getDefAddrFunc() {
				const response = await queryDefAddrApi({
					uid: this?.member?.id ?? "",
				}).catch(() => {})
				if (response?.code === 200) {
					this.addrData = response?.data ?? {};
				} else {
					this.addrData = {};
				};
			},

			// 计算实际支付 总金额
			calcTotalMoney() {
				// 服务项总金额
				let service_money = 0;

				this.goods_money = 0;
				this.goodsDatas.forEach(x => {
					x.goodsPrice = parseFloat(x.sprice);
					x.goodsStock_num = x.pcount;
					console.debug(x, "<==============xxxxxxxxxxxx")
					// if (x.cart && x.cart.goods_num) {
					// 	x.goods.goods_num = x.cart.goods_num;
					// }

					this.goods_money += (x.goodsPrice) * x.goodsStock_num;
					console.log(this.goods_money, "<==== goods_money")
					// this.goods_money += (x.sprice) * x.pcount;
				});
				this.goods_money =this.goods_money.toFixed(2);

				//实付款
				// this.total_money = this.goods_money;
				
				// 商品金额 + 服务金额 - 优惠金额
				
				// 直减券
				if (this.coupon_type == 1) {
					// 优惠金额
					this.total_coupon_money = this.coupon_money;
					
					// 如果商品总额大于或等于优惠券总金额
					if((this.goods_money + service_money) >= this.coupon_money){
						// 商品总价
						this.total_money = (this.goods_money + service_money - this.coupon_money).toFixed(2);
					}else{
						// 优惠券总金额大于或等于商品总额
						this.total_coupon_money =(this.goods_money + service_money).toFixed(2);
						//商品总价
						this.total_money = 0;
					}
				} 
				// 折扣券
				else if (this.coupon_type == 0) {
					this.total_coupon_money = ((this.goods_money + service_money) - ((this.goods_money + service_money) *
						this.coupon_money).toFixed(2)).toFixed(2);
					this.total_money = ((this.goods_money + service_money) * this.coupon_money).toFixed(2);
				}
			},
			// +- 下单数量
			numberChange(options) {
				let data = this.goodsDatas[options.index];
				// data.goods.goods_num = options.number;
				data.pcount = options.pcount;

				// if (this.goods_id) this.goods_num = options.number;


				this.calcTotalMoney();
			},
			// 打开优惠券
			couponOpen() {
				let _this = this;
				// 加载可使用优惠券数据 couponDatas
				this.getUserCouponsFunc();
				

			},
			// 使用优惠券
			couponUse(coupon) {
				console.log(coupon,"<==============user.coupon")
				let _this = this;

				_this.order_coupon_id = coupon.users_coupons.id;
				
				if(coupon.price >= 0){
					// 优惠券直减金额
					_this.coupon_money = coupon.price;					
				
				}else{
					// 优惠券折扣
					_this.coupon_money = coupon.price;
				}
				
				// 折扣券
				if(coupon.type == 0){
					_this.coupon_type = 0;
				}
				// 直减券
				if(coupon.type == 1){
					_this.coupon_type = 1;
				}
				
				_this.couponName = coupon.title;

				_this.calcTotalMoney();

				_this.couponShow = false;
			},
			// 提交订单
			async submit() {
				// 使用的优惠券id
				// order_coupon_id: this.order_coupon_id;
				
				if (this.member.totals < this.total_money) {
					this.$api.msg('余额不足！！！');
					return;
				}

				if (!(this.addrData && this.addrData.id)) {
					this.$api.msg('请选择收货人');
					return;
				}

				if (this.is_submit) {
					this.$api.msg('提交中');
					return;
				}
				this.is_submit = 1;

				let _this = this;

				const list = this.goodsDatas.map((item) => {return { pid: item.id, pcount: item.pcount, sprice: item.sprice} });
				const response = await createOrdersApi({
					uid: this?.member?.id ?? "",
					totals: this?.total_money ?? "",
					products: list,
					remark: this?.order_desc ?? "",
					aid: this?.addrData?.id ?? "",
					couponTotals: this?.total_coupon_money ?? 0.00,
					// sprice: this?.goodsDatas?.sprice ?? 0,

				}).catch(() => {});
				if (response?.code === 200) {
					this.updateUserCouponsFunc();
					uni.navigateBack();
					this.$api.msg('订单支付成功');

				}


				// let obj = {
				// 	cart_ids: _this.cart_ids,

				// 	goods_id: _this.goods_id,
				// 	goods_num: _this.goods_num,
				// 	// goods_sku_id: _this.goods_sku_id,

					
				// 	order_integral: 0,
				// 	order_use_integral: 0,
				// 	addr_id: _this.addrData._id,
				// 	order_from: _this.platform_name,
				// 	// order_desc: _this.order_desc
				// 	order_desc: _this.remark
				// };

				// 	this.$func.usemall.call('order/create', obj).then(res => {
				// 		if (res.code === 200) {
				// 			// 跳转支付页
				// 			_this.$api.topay({
				// 				order_id: res.datas.order_id,
				// 				money: res.datas.money,
				// 				type: 'redirect'
				// 			});
				// 			return;
				// 		}

				// 		_this.$api.msg(res.msg);
				// 		_this.$api.timerout(() => {
				// 			_this.is_submit = 0;
				// 		}, 800);
				// 	})


			},
			// 选择收货人
			toaddr() {
				// this.addrData = {};
				// console.debug(this.addrData,"<=================toaddr")
				uni.navigateTo({
					url: '/pages/user/address/address?source=1',
					complete() {}
				});
			},
			
			
			//查询用户优惠券
			async getUserCouponsFunc(){
				this.couponDatas = [];
				
				const response = await queryUserCouponsApi({
					uid: this?.member?.id ?? "",
					state: 0,
				}).catch(() => {});
				if (response?.code === 200) {
				// 	const _data = [...this.orderList, ...(response?.data?.records ?? [])];
				this.couponDatas = [...this.couponDatas, ...(response?.data?.records ?? [])];
				// this.couponDatas =	this.couponDatas.map(item =>({
				// 	let item.state = item.users.users_coupons.state
				// }))
				
				// this.couponDatas = this.couponDatas.map(item => {
				//   // 创建一个新的对象，包含原来的属性和新添加的 state 字段
				//   return {
				//     ...item, // 将原来的属性拷贝到新对象中
				//     state: item?.users[0]?.users_coupons?.state // 添加新的 state 字段
				//   };
				// });
			
				console.log(this.couponDatas, "<=====couponDatas===========getUserCouponsFunc111");
				
				// this.new_time = new Date().getTime();
				
				
				
				// this.couponDatas = this.couponDatas.map(item => {
				// 	// if(item.users_coupons.state === 0 ){
				// 		let dateString  = item.end_time;
				// 		let dateObj = new Date(dateString).getTime();
				// 		if(this.new_time > dateObj){
				// 			if(item.users_coupons.state == 0){
				// 				this.new_status = 2;
				// 				this.updateUserCouponsFunc(item);
				// 			}
				// 		}else{
				// 			if(item.users_coupons.state == 2){
				// 				this.new_status = 0;
				// 				this.updateUserCouponsFunc(item);
				// 			}
				// 		}
						
				// 	// }
				// 	return item;
				//   // 创建一个新的对象，包含原来的属性和新添加的 state 字段
				//   // return {
				//   //   ...item, // 将原来的属性拷贝到新对象中
				//   //   state: item?.users[0]?.users_coupons?.state // 添加新的 state 字段
				//   // };
				// });
				
				
				console.log(this.couponDatas, "<=====couponDatas===========getUserCouponsFunc222");
			
				} else {
					this.$api.msg(response?.msg ?? '服务器繁忙，请稍后再试');
				}
			},
			
			// 修改优惠券状态为已使用
			async updateUserCouponsFunc(){
				const response = await updateUserCouponsApi({
					id: this?.order_coupon_id ?? "",
					state: 1,
				}).catch(() => {})
				if(response.code == 200){
					return;
				}else{
					this.$api.msg(response?.msg ?? "服务器繁忙，请稍后再试");
				}
			},
			
			
			
		}
	};
</script>

<style lang="scss">
	page {
		background: $page-color-base;
		padding-bottom: 100rpx;
	}

	.goods-area {
		.goods-item {
			display: flex;

			.disabled {
				color: #fff !important;
				width: 70%;
				height: 70%;
				background-color: rgba(51, 51, 51, 0.5);
			}

			image {
				flex-shrink: 0;
				display: block;
				width: 180rpx;
				height: 180rpx;
				border-radius: 4rpx;
			}
		}
	}

	.oper-area {
		z-index: 998;
		box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);

		.submit {
			width: 280rpx;
			height: 100rpx;
		}
	}

	/* 优惠券区 */
	.coupon-area {
		max-height: 60vh;
		overflow: auto;

		.coupon-item {
			margin-bottom: 20rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.content {
				&:after {
					position: absolute;
					left: 0;
					bottom: 0;
					content: '';
					width: 100%;
					height: 0;
					border-bottom: 1px dashed #f3f3f3;
					transform: scaleY(50%);
				}
			}

			.circle {
				position: absolute;
				bottom: -10rpx;
				z-index: 10;
				width: 20rpx;
				height: 20rpx;
				background: #f5f5f5;
				border-radius: 50%;

				&.r {
					right: -6rpx;
				}

				&.l {
					left: -6rpx;
				}
			}
		}
	}

	.coupon-none {
		width: 100%;
		height: 100%;
		line-height: 30vh;
		display: flex;
		align-items: center;
		justify-content: center;

		.coupon-none-tip {
			color: #909399;
		}
	}
</style>